//: \$dmd2 \console -L+pcre \+..\jade \+..\dmdscript \clean -O -release -inline

module jade.examples.scgi;

import std.socket, std.stdio, std.file, jade.Jade, std.process, core.memory;
version(Windows){}else{
	pragma(lib, "jade");
	pragma(lib, "pcre");
}

void main ( )
{
	Tpl_Factory.Init("./tpl.js") ;
	
	auto user_list	= Tpl_Factory.Create("UserList", "./example.jade" );
		
	user_list.assign( "Jade4D test pag", "page_title");
	
	user_list.assign(environment.toAA, "env");
	
	string[string] items ;
	items["one"] = "One";
	items["2"] = "Two";
	items["3"] = "Three";
	user_list.assign(items, "items");
	
	auto user = new User ;
	user_list.assign(user, "user");
	
	//writefln("%b" , x"0d 0a");
	//stdout.flush;
	auto addr	= new InternetAddress(1984);
	auto ssoc	= new TcpSocket();
	scope(exit){
		Log("Exit");
                ssoc.shutdown(SocketShutdown.BOTH);
		ssoc.close;
	}
	ssoc.blocking(true);
        ssoc.bind(addr);
        ssoc.listen(32);
	
	auto bu	= new vBuffer(1024 * 32, 1024 * 32);
	bool isLoop	= true ;
	while(isLoop){
		scope soc	= ssoc.accept;
		scope(exit) soc.close;
		ubyte[1024 * 4] tmp;
		int i	= soc.receive(tmp);
		
		//writefln("len:%d", i);
		//writefln( "`%s`", cast(string) tmp[0..i] );
		//write( tmp[0..i] );
		
		foreach(ref c; tmp[0..i]) if( c is '\0') c = '\n';

		if( indexOf(cast(string)tmp[0..i], "exit=1") >= 0 ) {
			isLoop	= false ;
		}
		
		user_list.assign( cast(string) tmp[0..i], "header");
		
		StopWatch sw;
		sw.start;
		string _html = user_list.render ;
		sw.stop;
		
		bu.clear;
		bu("Status: 200 OK" x"0d 0a");
		bu("Content-Type: text/html" x"0d 0a");
		bu("Render-Time: ")(sw.peek.msecs)( "ms " x"0d 0a");
		bu("Content-Length: ")( _html.length)( x"0d 0a");
		bu(x"0d 0a");
		bu(_html);
		
		user.id ++ ;
		user.login	= !user.login;
		if( user.id % 3 is 0 )
			user.admin	= !user.admin;
		
		soc.send( bu.slice );
	}
}


private class User {
	int id	= 1983 ;
	bool login	= true ;
	bool admin	= false ;
	string name		= "Chang Long";
}
